using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;

namespace Nakio.Framework.Communication
{
    [DataContract]
    public class EncryptToken
    {
        [DataMember]
        public byte[] Key { get; private set; }
        [DataMember]
        public byte[] IV { get; private set; }

        public EncryptToken()
        {
            Key = new byte[32];
            IV = new byte[16];

            var rndKey = new Random();
            var rndIV = new Random(rndKey.Next());
            
            rndKey.NextBytes(Key);
            rndIV.NextBytes(IV);
        }

        public byte[] Encrypt(byte[] data)
        {
            var ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            
            alg.Key = Key;            
            alg.IV = IV;

            var cs = new CryptoStream(ms,
               alg.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(data, 0, data.Length);
            cs.Close();

            return ms.ToArray(); 
        }

        public byte[] Decrypt(byte[] data)
        {
            var ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();      

            alg.Key = Key;
            alg.IV = IV;

            var cs = new CryptoStream(ms,
                alg.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(data, 0, data.Length);
            cs.Close();

            return ms.ToArray();
        }
    }
}